package com.bignerdranch.android.furnitureapplication.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bignerdranch.android.furnitureapplication.ContentActivity;
import com.bignerdranch.android.furnitureapplication.R;
import com.bignerdranch.android.furnitureapplication.entity.NewsInfoBean;
import com.bumptech.glide.Glide;

import java.util.List;

public class NewsInfoAdapter extends RecyclerView.Adapter<NewsInfoAdapter.ViewHolder> {

    private Context mContext;
    private List<NewsInfoBean> dataList;
    public static final String NEWS_ID = "news _id";

    public class ViewHolder extends RecyclerView.ViewHolder {

        LinearLayout newsItem;
        ImageView newsImage;
        TextView newsText;

        public ViewHolder(View itemView) {
            super(itemView);
            newsImage = itemView.findViewById(R.id.latest_news_image);
            newsItem = itemView.findViewById(R.id.news_item);
            newsText = itemView.findViewById(R.id.latest_news_title);
        }
    }

    public NewsInfoAdapter(List<NewsInfoBean> dataList) {
        this.dataList = dataList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mContext == null) {
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.new_info_item, parent, false);
        final ViewHolder viewHolder = new ViewHolder(view);
        viewHolder.newsItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = viewHolder.getAdapterPosition();
                NewsInfoBean newsInfoBean = dataList.get(position);
                int id = newsInfoBean.getId();
                Intent intent = new Intent(mContext, ContentActivity.class);
                intent.putExtra(NEWS_ID, id);
                intent.putExtra("web_url", newsInfoBean.getKnowUrl());
                mContext.startActivity(intent);
            }
        });
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        NewsInfoBean newsInfoBean = dataList.get(position);
        holder.newsText.setText(newsInfoBean.getKnowTitle());
        Glide.with(mContext).load(newsInfoBean.getKnowImages()).into(holder.newsImage);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }
}
